package hl.crazy_java.chapter_16;

/**
 * java线程同步--可重入锁 RreentrantLock()
 *
 * @author Liu Huan
 */

import java.util.concurrent.locks.ReentrantLock;

/**
 * 账户类：包含 账户id  和  账户余额
 */
public class Account {
    // 生成一个 可重入锁 对象
    private final ReentrantLock rk = new ReentrantLock();

    private String id;
    private int balance;

    public Account(String id,int balance){
        this.id = id;
        this.balance = balance;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    /**
     * 替换原来的 setBalance() 使用 synchronized 修饰，变成 同步方法
     * @param drawAmount
     */
    public synchronized void draw(int drawAmount) {
        //加锁
        rk.lock();
        try {
            if (balance>drawAmount){
                System.out.println(Thread.currentThread().getName() + "取钱成功" + "金额：" + drawAmount);
                balance -= drawAmount;
                System.out.println(Thread.currentThread().getName() + "取后，账户余额：" + balance);
            } else {
                System.out.println(Thread.currentThread().getName() + "取钱失败");
            }
        }
        finally {
            // 解锁
            rk.unlock();
        }

    }

    public int getBalance() {
        return balance;
    }
}

/**
 * 取钱线程
 * acc 接收 传进来的 账户对象的引用
 * drawAmount  要取的 钱的总量
 * 直接调用 账户的 取钱方法 draw()
 */
class DrawMoney extends Thread {

    private Account acc;
    private int drawAmount;
    // 取钱线程的名字  取钱的账户  取钱的总量
    public DrawMoney(String name, Account acc, int drawAmount){
        super(name);
        this.acc = acc;
        this.drawAmount = drawAmount;
    }

    @Override
    public void run() {
        // 调用 取钱 同步方法
        acc.draw(drawAmount);
    }
}

class DrawTest {
    public static void main(String[] args) throws InterruptedException {
        var acct = new Account("1234",1000);
        var p = new DrawMoney("甲", acct, 800);
        p.start();

        var pp = new DrawMoney("乙", acct, 800);
        pp.start();

        var ppp = new DrawMoney("丙", acct, 800);
        ppp.start();
    }
}